/*
 * ======== Standard MSP430 includes ========
 */
#include <msp430.h>

/*
 * ======== Grace related includes ========
 */
#include <ti/mcu/msp430/csl/CSL.h>
#include <inttypes.h>
#include <string.h>
#include "hal.h"

void checkButton(void);

static uint32_t gSystemTicks = 0;
static char gBuf[100];
static uint16_t gCurrBuf = 0;

#define DIT_TIME			200
#define DAH_TIME			(3 * DIT_TIME)
#define PAUSE_TIME			DAH_TIME
#define false 0
#define true 1

static uint32_t getSystemTicks(void);

void ATOMIC_START(void) {
	__disable_interrupt();
}

void ATOMIC_END(void) {
	__enable_interrupt();
}

/*
 *  ======== main ========
 */
int main(int argc, char *argv[]) {
	CSL_init(); // Activate Grace-generated configuration

	P1OUT |= BIT3;
	P1REN |= BIT3;
	P1IE |= BIT3; // interrupt for button
	P1IFG &= ~BIT3; // clear flag register

	while (1) {
	}
}

#pragma vector=PORT1_VECTOR
__interrupt void checkButton(void) {
	static uint32_t prevTime = 0;
	static uint16_t released = false;

	if (released) {
		released = false;
		uint32_t diff = getSystemTicks() - prevTime;
		if (diff >= DAH_TIME) {
			gBuf[gCurrBuf] = 'x';
		} else {
			gBuf[gCurrBuf] = 'y';
		}
		gCurrBuf++;
	} else if(prevTime > 0) {
		released = true;
	}

	prevTime = getSystemTicks();

	P1OUT ^= BIT0;
	P1IFG &= ~BIT3; // clear flag register
	P1IES ^= BIT3; // toggle interrupt edge
}

void timerMillisecondPassed(void) {
	gSystemTicks++;
}

uint32_t getSystemTicks() {
	halIntState_t s;

	HAL_ENTER_CRITICAL_SECTION(s);
	uint32_t t = gSystemTicks;
	HAL_EXIT_CRITICAL_SECTION(s);

	return t;
}
